"""基础智能体类"""

import asyncio
import logging
from typing import Any, Dict, List, Optional, Set
from datetime import datetime
from .agent_state import AgentState, AgentStatus, Task, TaskStatus
from .agent_interface import AgentInterface


class BaseAgent(AgentInterface):
    """基础智能体类"""
    
    def __init__(
        self,
        agent_id: str,
        name: str,
        capabilities: Set[str],
        max_retries: int = 3,
        timeout: int = 300
    ):
        self.agent_id = agent_id
        self.name = name
        self.capabilities = capabilities
        self.max_retries = max_retries
        self.timeout = timeout
        
        self.state = AgentState(
            agent_id=agent_id,
            name=name,
            capabilities=capabilities
        )
        
        self.logger = logging.getLogger(f"agent.{agent_id}")
        self._is_initialized = False
    
    async def initialize(self) -> None:
        """初始化智能体"""
        if self._is_initialized:
            return
        
        self.logger.info(f"初始化智能体: {self.name}")
        await self._setup()
        self._is_initialized = True
        self.state.status = AgentStatus.IDLE
    
    async def process_task(self, task: Task) -> Dict[str, Any]:
        """处理任务"""
        if not self._is_initialized:
            await self.initialize()
        
        if self.state.status != AgentStatus.IDLE:
            raise RuntimeError(f"智能体 {self.name} 当前状态为 {self.state.status}，无法处理新任务")
        
        self.state.status = AgentStatus.BUSY
        self.state.current_task = task
        task.status = TaskStatus.IN_PROGRESS
        task.started_at = datetime.now()
        
        try:
            self.logger.info(f"开始处理任务: {task.name}")
            result = await self._execute_task(task)
            
            task.status = TaskStatus.COMPLETED
            task.completed_at = datetime.now()
            self.state.success_count += 1
            
            self.logger.info(f"任务完成: {task.name}")
            return result
            
        except Exception as e:
            self.logger.error(f"任务失败: {task.name}, 错误: {str(e)}")
            task.status = TaskStatus.FAILED
            self.state.error_count += 1
            raise
            
        finally:
            self.state.status = AgentStatus.IDLE
            self.state.current_task = None
            self.state.last_activity = datetime.now()
    
    async def get_capabilities(self) -> List[str]:
        """获取智能体能力"""
        return list(self.capabilities)
    
    async def get_status(self) -> AgentState:
        """获取智能体状态"""
        return self.state
    
    async def update_context(self, context: Dict[str, Any]) -> None:
        """更新上下文"""
        self.state.context.update(context)
        self.logger.debug(f"更新上下文: {context}")
    
    async def reset(self) -> None:
        """重置智能体"""
        self.state.status = AgentStatus.IDLE
        self.state.current_task = None
        self.state.context.clear()
        self.state.error_count = 0
        self.state.success_count = 0
        self.logger.info(f"重置智能体: {self.name}")
    
    async def cleanup(self) -> None:
        """清理资源"""
        if self.state.status == AgentStatus.BUSY:
            await self.reset()
        self.state.status = AgentStatus.OFFLINE
        self.logger.info(f"清理智能体: {self.name}")
    
    async def _setup(self) -> None:
        """子类实现：设置智能体"""
        pass
    
    async def _execute_task(self, task: Task) -> Dict[str, Any]:
        """子类实现：执行具体任务"""
        raise NotImplementedError("子类必须实现 _execute_task 方法")
